package com.cn.kabalifeuser.ui.order.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.LazyFragment;
import com.cn.kabalifeuser.callback.SchedulerTransformer;
import com.cn.kabalifeuser.config.Constants;
import com.cn.kabalifeuser.config.CustomRefreshListener;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.RefreshHelper;
import com.cn.kabalifeuser.event.RxBus;
import com.cn.kabalifeuser.event.RxBusBean;
import com.cn.kabalifeuser.event.RxBusBooleanBean;
import com.cn.kabalifeuser.ui.integral.bean.WxPayBean;
import com.cn.kabalifeuser.ui.login.bean.MsgBean;
import com.cn.kabalifeuser.ui.order.activity.CommentAddActivity;
import com.cn.kabalifeuser.ui.order.activity.IExpressActivity;
import com.cn.kabalifeuser.ui.order.activity.MallOrderDetailsActivity;
import com.cn.kabalifeuser.ui.order.adapter.OrderItemAdapter;
import com.cn.kabalifeuser.ui.order.bean.OrderListAfterSaleBean;
import com.cn.kabalifeuser.ui.order.bean.OrderListListBean;
import com.cn.kabalifeuser.ui.release.bean.PayResult;
import com.cn.kabalifeuser.ui.release.bean.ZfbBean;
import com.cn.kabalifeuser.utils.GsonUtil;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifeuser.view.PopupWindow.CommonUtil;
import com.cn.kabalifeuser.view.dialogView.PayErrDialog;
import com.kongzue.dialog.v2.SelectDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by 晓林 on 2020/9/7.
 * function:
 */
public class MallOrderFragments extends LazyFragment<MallFragmentslView, MallFragmentsPresenter> implements MallFragmentslView, CommonPopupWindow.ViewInterface {
    @BindView(R.id.rv_notice)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private View notDataView;
    List<OrderListListBean.ResultBean.DataBean> mList;
    OrderAdapter mAdapter;
    private int mId;
    private CommonPopupWindow popupWindowPay;

    int orderID = -1;

    public static MallOrderFragments getInstance(int mid) {
        MallOrderFragments fragment = new MallOrderFragments();
        fragment.mId = mid;
        return fragment;
    }

    @Override
    protected MallFragmentsPresenter createPresenter() {
        return new MallFragmentsPresenter();
    }

    @Override
    protected void onUserVisible() {
        if (mList != null && mList.size() == 0) {
            pagehttp = 1;
            getListData();
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.recyclerview_refresh;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        ButterKnife.bind(this, view);
        mList = new ArrayList<>();
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager3.setSmoothScrollbarEnabled(true);
        layoutManager3.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(layoutManager3);
        recyclerView.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new OrderAdapter(R.layout.fragment_order_mall_item, mList, mId);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(mAdapter);
        notDataView = getLayoutInflater().inflate(R.layout.show_empty_view, (ViewGroup) recyclerView.getParent(), false);
        notDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("sign", mId);
                bundle.putInt("id", mAdapter.getItem(position).getId());
                $startActivity(MallOrderDetailsActivity.class, bundle);
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_btn_colce:
                        //todo 取消订单
                        SelectDialog.show(getMe(), "提示", "确定要取消该订单吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.onOrderSetData(LoginHelper.getLonginData().getResult(), 0, mAdapter.getItem(position).getId());
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        break;
                    case R.id.tv_btn_pay:
                        //todo 支付
                        orderID = mAdapter.getItem(position).getId();
                        showPay();
                        break;
                    case R.id.tv_btn_logistics:
                        //todo 物流
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", mAdapter.getItem(position).getId());
                        $startActivity(IExpressActivity.class, bundle);
                        break;
                    case R.id.tv_btn_confirm:
                        //todo 确认收货
                        SelectDialog.show(getMe(), "提示", "确定要收货吗？", "确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.onOrderSetData(LoginHelper.getLonginData().getResult(), mAdapter.getItem(position).getId());
                            }
                        }, "取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });

                        break;
                    case R.id.tv_btn_comment:
                        //todo 评价
                        bundle = new Bundle();
                        bundle.putString("s_Good_img", mAdapter.getItem(position).getGoods().get(0).getGood_img());
                        bundle.putString("s_Title", mAdapter.getItem(position).getGoods().get(0).getTitle());
                        bundle.putString("s_Spec_key", mAdapter.getItem(position).getGoods().get(0).getSpec_key());
                        bundle.putString("s_Original_price", mAdapter.getItem(position).getGoods().get(0).getOriginal_price());
                        bundle.putInt("s_Good_num", mAdapter.getItem(position).getGoods().get(0).getGood_num());
                        bundle.putString("s_Created_at", mAdapter.getItem(position).getGoods().get(0).getCreated_at());
                        bundle.putInt("id", mAdapter.getItem(position).getId());
                        $startActivity(CommentAddActivity.class, bundle);
                        break;
                }
            }
        });
        initRefreshLayout();


        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean.class)
                .compose(new SchedulerTransformer<RxBusBean>())
                .subscribe(new Action1<RxBusBean>() {
                    @SuppressLint("WrongConstant")
                    @Override
                    public void call(RxBusBean rxBusBean) {
                        if (rxBusBean.getSign() == 1111 && rxBusBean.getId() == 1111) {
                            //详情操作成功以后。
                            pagehttp = 1;
                            getListData();
                        } else if (rxBusBean.getId() == 2002 && rxBusBean.getSign() == 2002) {
                            RxToast.success("支付成功");
                            Constants.PAY_SIGN = 0;
                            refreshLayout.autoRefresh();
                        }
                    }
                });


    }

    /**
     * 规格
     */
    private void showPay() {
        if (popupWindowPay != null && popupWindowPay.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_commodity_pay, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowPay = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_commodity_pay)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowPay.showAtLocation(getActivity().findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }


    int paySign = 1;

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            //todo 支付
            case R.layout.pw_commodity_pay:
                ImageView img_check_weixin = view.findViewById(R.id.img_check_weixin);
                ImageView img_check_zfb = view.findViewById(R.id.img_check_zfb);
                img_check_weixin.setImageResource(R.drawable.check_true);
                img_check_zfb.setImageResource(R.drawable.check_false);
                paySign = 1;
                view.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Constants.PAY_SIGN = 0;
                        if (popupWindowPay != null)
                            popupWindowPay.dismiss();
                        refreshLayout.autoRefresh();
                    }
                });
                view.findViewById(R.id.ll_btn_pay_zfb).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        img_check_weixin.setImageResource(R.drawable.check_false);
                        img_check_zfb.setImageResource(R.drawable.check_true);
                        paySign = 2;
                    }
                });
                view.findViewById(R.id.ll_btn_pay_weixin).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        img_check_weixin.setImageResource(R.drawable.check_true);
                        img_check_zfb.setImageResource(R.drawable.check_false);
                        paySign = 1;
                    }
                });
                view.findViewById(R.id.ll_btn_pay_qianbao).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayErrDialog payErrDialog=new PayErrDialog(getMe());
                        payErrDialog.show();
                    }
                });
                view.findViewById(R.id.ll_btn_pay_yinlian).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PayErrDialog payErrDialog=new PayErrDialog(getMe());
                        payErrDialog.show();
                    }
                });
                view.findViewById(R.id.tv_btn_pay).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.onOrderPayData(LoginHelper.getLonginData().getResult(), orderID, paySign
                        );

                    }
                });
                break;
        }
    }

    /**
     * 刷新
     */
    public void initRefreshLayout() {
        RefreshHelper.initRefreshLayout(refreshLayout, new CustomRefreshListener() {
            @Override
            public void _onRefresh(RefreshLayout refreshLayout) {
                pagehttp = 1;
                getListData();
            }

            @Override
            public void _onLoadMore(RefreshLayout refreshLayout) {
                pagehttp++;
                if (null != mList) {
                    getListData();
                }
            }
        });
    }

    private void getListData() {
//        mList.add("待付款");
//        mList.add("待发货");
//        mList.add("待收货");
//        mList.add("待评价");
//        mList.add("售后");
        if (mId == 0)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 0, pagehttp, pageNum);
        else if (mId == 1)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 1, pagehttp, pageNum);
        else if (mId == 2)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 2, pagehttp, pageNum);
        else if (mId == 3)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 3, pagehttp, pageNum);
        else if (mId == 4)
            mPresenter.onOrderGoodsListData(LoginHelper.getLonginData().getResult(), 4, pagehttp, pageNum);
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        RxToast.error(msg);

    }

    @Override
    public Context _getContext() {
        return null;
    }

    @Override
    public void onOrderListSuccess(OrderListListBean bean) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        if (pagehttp == 1) {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.replaceData(bean.getResult().getData());
            } else {
                mAdapter.replaceData(bean.getResult().getData());
                mAdapter.setEmptyView(notDataView);
            }
        } else {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.addData(bean.getResult().getData());
            }

        }
    }

    @Override
    public void onOrderSetSuccess(MsgBean bean) {
        //操作。
        RxToast.success(bean.getMsg());
        refreshLayout.autoRefresh();
    }

    @Override
    public void onOrderPaySuccess(String json) {
        if (paySign == 2) {
            //todo 支付宝
            ZfbBean bean = GsonUtil.GsonToJsonClass(json, ZfbBean.class);
            if (bean.getCode() == Constants.HTTP_SUCCESS) {
                //TODO 支付宝支付
                final String orderInfo = bean.getResult();
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(
                                getActivity());
                        Map<String, String> result = alipay
                                .payV2(orderInfo, true);
                        LoggerUtils.d("支付宝数据:" + result.toString());
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if (bean.getCode() == Constants.HTTP_AGAIN_LOGIN) {
                onReLoggedIn(bean.getMsg());
            } else onError(bean.getMsg());
        } else if (paySign == 1) {
            //todo 微信
            WxPayBean bean = GsonUtil.GsonToJsonClass(json, WxPayBean.class);
            if (bean.getCode() == Constants.HTTP_SUCCESS) {
                Constants.PAY_SIGN = 2002;
                IWXAPI api = WXAPIFactory.createWXAPI(getMe(), bean.getResult().getAppid());
                api.registerApp(bean.getResult().getAppid());
                PayReq req = new PayReq();
                req.appId = bean.getResult().getAppid();
                req.partnerId = bean.getResult().getPartnerid();  //商户id
                req.prepayId = bean.getResult().getPrepayid(); //预支付交易会话ID
                req.packageValue = bean.getResult().getPackageX(); //扩展字段
                req.nonceStr = bean.getResult().getNoncestr(); //随机字符串
                req.timeStamp = String.valueOf(bean.getResult().getTimestamp());//时间戳
                req.sign = bean.getResult().getSign(); //签名
                api.sendReq(req);
            } else if (bean.getCode() == Constants.HTTP_AGAIN_LOGIN) {
                onReLoggedIn(bean.getMsg());
            } else onError(bean.getMsg());

        }
    }

    @Override
    public void onOrderAfterSaleListSuccess(OrderListAfterSaleBean bean) {

    }

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(
                            (Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        LoggerUtils.d("支付宝支付成功咯~~~");
                        RxToast.success("支付成功");
                        if (popupWindowPay != null)
                            popupWindowPay.dismiss();
                        refreshLayout.autoRefresh();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        LoggerUtils.d("支付宝支付失敗了~~~");
                        RxToast.error("支付失败!");

                    }
                    break;
                }
                default:
                    break;
            }
        }


    };


    class OrderAdapter extends BaseQuickAdapter<OrderListListBean.ResultBean.DataBean, BaseViewHolder> {

        int mId;

        public OrderAdapter(int layoutResId, @Nullable List<OrderListListBean.ResultBean.DataBean> data, int mId) {
            super(layoutResId, data);
            this.mId = mId;
        }

        @Override
        protected void convert(BaseViewHolder helper, final OrderListListBean.ResultBean.DataBean item) {
            helper.setText(R.id.tv_total_amount, item.getTotal_amount())
                    .setText(R.id.tv_number, String.valueOf(item.getNum()));
            TextView tvStatus = helper.getView(R.id.tv_status);
            // 0：已取消，1：待支付，2：已支付，3：退款，4:待收货，5：已完成
            if (item.getGoods().get(0).getStatus() == 0) {
                helper.setGone(R.id.tv_no, false);
                helper.setGone(R.id.tv_num, false);
                tvStatus.setText("已取消");
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_logistics, false);
                helper.setGone(R.id.tv_btn_confirm, false);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (item.getGoods().get(0).getStatus() == 2) {
                helper.setGone(R.id.tv_no, false);
                helper.setGone(R.id.tv_num, false);
                tvStatus.setText("买家已付款");
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_logistics, false);
                helper.setGone(R.id.tv_btn_confirm, false);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (item.getGoods().get(0).getStatus() == 3) {
                helper.setGone(R.id.tv_no, false);
                helper.setGone(R.id.tv_num, false);
                tvStatus.setText("已退款");
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_logistics, false);
                helper.setGone(R.id.tv_btn_confirm, false);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (item.getGoods().get(0).getStatus() == 4) {
                helper.setGone(R.id.tv_no, false);
                helper.setGone(R.id.tv_num, false);
                tvStatus.setText("买家已发货");
                helper.setText(R.id.tv_number, String.valueOf(item.getNum()));
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_logistics, true);
                helper.setGone(R.id.tv_btn_confirm, true);
                helper.setGone(R.id.tv_btn_comment, false);
            } else if (item.getGoods().get(0).getStatus() == 5) {
                helper.setGone(R.id.tv_no, false);
                helper.setGone(R.id.tv_num, false);
                tvStatus.setText("交易完成");
                helper.setGone(R.id.tv_btn_colce, false);
                helper.setGone(R.id.tv_btn_pay, false);
                helper.setGone(R.id.tv_btn_logistics, false);
                helper.setGone(R.id.tv_btn_confirm, false);
                if (item.getGoods().get(0).getIs_review() == 1)
                    helper.setGone(R.id.tv_btn_comment, false);
                else helper.setGone(R.id.tv_btn_comment, true);
            }


            helper.addOnClickListener(R.id.tv_btn_colce);
            helper.addOnClickListener(R.id.tv_btn_pay);
            helper.addOnClickListener(R.id.tv_btn_logistics);
            helper.addOnClickListener(R.id.tv_btn_confirm);
            helper.addOnClickListener(R.id.tv_btn_comment);
            RecyclerView rvData = helper.getView(R.id.rv_data);
            LinearLayoutManager layoutManager3 = new LinearLayoutManager(getMe());
            layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
            layoutManager3.setSmoothScrollbarEnabled(true);
            layoutManager3.setAutoMeasureEnabled(true);
            rvData.setLayoutManager(layoutManager3);
            rvData.setNestedScrollingEnabled(false);
            //创建适配器
            OrderItemAdapter mAdapter = new OrderItemAdapter(R.layout.order_list_item, item.getGoods());
            //给RecyclerView设置适配器
            rvData.setAdapter(mAdapter);

            mAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("sign", mId);
                    bundle.putInt("id", item.getId());
                    $startActivity(MallOrderDetailsActivity.class, bundle);
                }
            });
        }


    }
}



